<template>
  <div class="app-container">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="app-header">
        <div class="header-left">
          <h2>管理系统后台</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleUserCommand">
            <div class="user-info">
              <el-avatar :size="32" style="margin-right: 12px;">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ userStore.userName }}</span>
              <el-icon style="margin-left: 8px;"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item command="password">
                  <el-icon><Lock /></el-icon>
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <el-aside class="app-sidebar" width="240px">
          <div class="admin-panel">
            <el-avatar :size="40">管</el-avatar>
            <div class="admin-details">
              <div class="name">{{ userStore.userName }}</div>
              <div class="role">系统管理员</div>
            </div>
          </div>

          <el-menu
              :default-active="$route.path"
              router
              class="sidebar-menu"
              background-color="#001529"
              text-color="#a5b4fc"
              active-text-color="#ffffff"
          >
            <el-menu-item index="/admin">
              <el-icon><Monitor /></el-icon>
              <span>管理首页</span>
            </el-menu-item>

            <el-sub-menu index="projects">
              <template #title>
                <el-icon><Management /></el-icon>
                <span>项目管理</span>
              </template>
              <el-menu-item index="/admin/projects">
                <el-icon><Folder /></el-icon>
                <span>项目总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/review">
                <el-icon><View /></el-icon>
                <span>审核中心</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="awards">
              <template #title>
                <el-icon><Trophy /></el-icon>
                <span>奖项管理</span>
              </template>
              <el-menu-item index="/admin/awards">
                <el-icon><List /></el-icon>
                <span>奖项总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/award-review">
                <el-icon><Check /></el-icon>
                <span>奖项审核</span>
              </el-menu-item>
            </el-sub-menu>

            <el-menu-item index="/admin/honors">
              <el-icon><Trophy /></el-icon>
              <span>人才与荣誉</span>
            </el-menu-item>

            <el-sub-menu index="party">
              <template #title>
                <el-icon><Flag /></el-icon>
                <span>党建管理</span>
              </template>
              <el-menu-item index="/admin/party-overview">
                <el-icon><DataBoard /></el-icon>
                <span>党建总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/party-review">
                <el-icon><Check /></el-icon>
                <span>党建审核</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="activities">
              <template #title>
                <el-icon><Calendar /></el-icon>
                <span>学术活动管理</span>
              </template>
              <el-menu-item index="/admin/activity-overview">
                <el-icon><DataBoard /></el-icon>
                <span>学术活动总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/activities">
                <el-icon><Check /></el-icon>
                <span>学术活动审核</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="academic">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>学术成果管理</span>
              </template>
              <el-menu-item index="/admin/academic-overview">
                <el-icon><DataBoard /></el-icon>
                <span>学术成果总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/academic-achievements">
                <el-icon><Check /></el-icon>
                <span>学术成果审核</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 新增：人才管理 -->
            <el-sub-menu index="talent">
              <template #title>
                <el-icon><User /></el-icon>
                <span>人才管理</span>
              </template>
              <el-menu-item index="/admin/student-guidance-overview">
                <el-icon><DataBoard /></el-icon>
                <span>人才培养总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/student-guidance">
                <el-icon><Check /></el-icon>
                <span>人才培养审核</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="influence">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>社会影响力</span>
              </template>
              <el-menu-item index="/admin/academic-positions">
                <el-icon><List /></el-icon>
                <span>学术兼职管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/social-services">
                <el-icon><List /></el-icon>
                <span>社会服务管理</span>
              </el-menu-item>
              <el-menu-item index="/admin/influence-stats">
                <el-icon><DataBoard /></el-icon>
                <span>社会影响力统计</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="textbook">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>教材/专著</span>
              </template>
              <el-menu-item index="/admin/textbooks">
                <el-icon><List /></el-icon>
                <span>教材/专著管理</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="serviceContribution">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>服务贡献</span>
              </template>
              <el-menu-item index="/admin/service-contrib-overview">
                <el-icon><DataBoard /></el-icon>
                <span>服务贡献总览</span>
              </el-menu-item>
              <el-menu-item index="/admin/service-contrib-review">
                <el-icon><Check /></el-icon>
                <span>服务贡献审核</span>
              </el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="course-hours">
              <template #title>
                <el-icon><Clock /></el-icon>
                <span>教学课时管理</span>
              </template>
              <el-menu-item index="/admin/course-hours-overview">
                <el-icon><DataBoard /></el-icon>
                <span>教学课时总览</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

        <!-- 主内容区域 -->
        <el-main class="main-content">
          <router-view />
        </el-main>
      </el-container>

      <!-- 修改密码对话框 -->
      <el-dialog v-model="showPasswordDialog" title="修改密码" width="500px">
        <el-form :model="passwordForm" label-width="100px">
          <el-form-item label="原密码">
            <el-input v-model="passwordForm.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="passwordForm.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordChange">确定</el-button>
        </template>
      </el-dialog>
    </el-container>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User, ArrowDown, Setting, SwitchButton, Bell, Lock,
  Monitor, Management, Folder, View, Trophy, List, Check, Document, DataBoard, Calendar
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'  // ✅ 修复导入
import { changePassword } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()  // ✅ 修复变量名

const showPasswordDialog = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      ElMessage.info('个人信息功能开发中...')
      break
    case 'password':
      showPasswordDialog.value = true
      break

    case 'logout':
      try {
        await ElMessageBox.confirm(
            '确定要退出登录吗？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        userStore.logout()  // ✅ 修复方法调用
        ElMessage.success('已退出登录')
        router.push('/login')
      } catch {
        // 取消退出
      }
      break
  }
}

const handlePasswordChange = async () => {
  if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword || !passwordForm.value.confirmPassword) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  if (passwordForm.value.oldPassword === passwordForm.value.newPassword) {
    ElMessage.error('新密码不能与原密码相同')
    return
  }

  try {
    await ElMessageBox.confirm('修改密码后需要重新登录，确定要继续吗？', '确认修改', {
      confirmButtonText: '确定修改',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await changePassword({ oldPassword: passwordForm.value.oldPassword, newPassword: passwordForm.value.newPassword })
    ElMessage.success('密码修改成功，请重新登录')
    showPasswordDialog.value = false

    // 重置表单
    passwordForm.value = { oldPassword: '', newPassword: '', confirmPassword: '' }

    // 触发退出登录
    userStore.logout()
    router.push('/login')
  } catch (err) {
    if (err !== 'cancel') {
      const status = err?.response?.status
      const serverMessage = err?.response?.data?.message || err?.response?.data || err?.message
      if (status === 400 || status === 422 || String(serverMessage || '').includes('旧密码') || String(serverMessage || '').includes('当前密码')) {
        ElMessage.closeAll()
        ElMessage.error('当前密码不正确')
      } else {
        ElMessage.error(typeof serverMessage === 'string' ? serverMessage : '修改密码失败')
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  height: 100vh;
}

.app-header {
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  z-index: 1001;
}

.header-left h2 {
  color: #333;
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
}

.notification-badge {
  margin-right: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s;
}

.user-info:hover {
  background: #f5f5f5;
}

.username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.app-sidebar {
  background: #001529;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.admin-panel {
  padding: 24px 20px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 16px;
}

.admin-details {
  margin-left: 12px;
  color: white;
}

.admin-details .name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
}

.admin-details .role {
  font-size: 12px;
  opacity: 0.7;
}

.sidebar-menu {
  border: none;
}

.sidebar-menu .el-sub-menu__title,
.sidebar-menu .el-menu-item {
  height: 48px;
  line-height: 48px;
  margin: 4px 12px;
  border-radius: 6px;
}

.sidebar-menu .el-menu-item.is-active {
  background: #1890ff !important;
  color: #ffffff !important;
}

.sidebar-menu .el-sub-menu .el-menu-item {
  background: transparent !important;
  margin: 0 24px;
  height: 40px;
  line-height: 40px;
}

.sidebar-menu .el-sub-menu .el-menu-item.is-active {
  background: rgba(24, 144, 255, 0.8) !important;
  border-radius: 4px;
}

.main-content {
  background: #f0f2f5;
  padding: 24px;
  height: calc(100vh - 60px);
  overflow-y: auto;
}
</style>